package com.lswms.modules.lswms.service.impl.base;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lswms.common.service.impl.CrudServiceImpl;
import com.lswms.modules.lswms.MEGConstant;
import com.lswms.modules.lswms.dao.base.SequenceDao;
import com.lswms.modules.lswms.dto.base.SequenceDTO;
import com.lswms.modules.lswms.entity.base.SequenceEntity;
import com.lswms.modules.lswms.service.base.SequenceService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 序号
 *
 * @author DX sunlightcs@gmail.com
 * @since 1.0.0 2021-06-14
 */
@Service
public class SequenceServiceImpl extends CrudServiceImpl<SequenceDao, SequenceEntity, SequenceDTO>
		implements SequenceService {

	@Override
	public QueryWrapper<SequenceEntity> getWrapper(Map<String, Object> params) {
		String id = (String) params.get("id");

		QueryWrapper<SequenceEntity> wrapper = new QueryWrapper<>();
		wrapper.eq(StringUtils.isNotBlank(id), "id", id);

		return wrapper;
	}

	@Override
	public String getSequence(String type) {
		// String type = (String)params.get("type");

		QueryWrapper<SequenceEntity> wrapper = new QueryWrapper<>();
		wrapper.eq("type", type);

		List<SequenceEntity> list = baseDao.selectList(wrapper);

		SequenceEntity entity = null;
		if (list.size() > 0) {
			entity = list.get(0);
		} else {
			return null;
		}

		Integer size = entity.getSize();
		String suffix = entity.getSuffix();

		String prefix = entity.getPrefix();
		Integer seed = entity.getSeed();
		Integer interval1 = entity.getInterval1();
		Integer present = entity.getPresent();

		suffix = null == suffix ? "" : suffix.trim();
		prefix = null == prefix ? "" : prefix.trim();
		// 剩余的长度
		int lastSize = size - suffix.length() - prefix.length();
		// 当前的有效值
		int currentInt = seed > present ? seed : present;
		// 增加后的值
		int nextInt = currentInt + interval1;
		// 取余
		int modInt = 1;
		for (int i = 0; i < lastSize; i++) {
			modInt *= 10;
		}
		currentInt = currentInt % modInt;

		entity.setPresent(nextInt);
		entity.setLasttime(new Date());

		// 更新记录
		baseDao.update(entity, wrapper);

		String returnValue = prefix + StringUtils.leftPad(nextInt + "", lastSize, '0') + suffix;

		return returnValue;
	}

	@Override
	public String validate(String type) {
		// String type = (String)params.get("type");
		if (StringUtils.isAllEmpty(type)) {
			return String.format(MEGConstant.IS_NOT_EMPTY, "type");
		}

		return null;
	}

}
